/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.juick.mod;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Toast;

import com.juick.mod.api.JuickMessage;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;

/**
 *
 * @author ugnich
 */
public class JuickMessageMenu implements OnItemLongClickListener, OnClickListener {

    Activity activity;
    JuickMessage listSelectedItem;
    ArrayList<String> urls;
    ArrayList<String> msgs;
    int menuLength;

    public JuickMessageMenu(Activity activity) {
        this.activity = activity;
    }

    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        listSelectedItem = (JuickMessage) parent.getAdapter().getItem(position);

        int pos = 0;
        Matcher m = JuickMessagesAdapter.urlPattern.matcher(listSelectedItem.Text);
        urls = null;
        while (m.find(pos)) {
            if (urls == null) { urls = new ArrayList<String>(); }
            urls.add(listSelectedItem.Text.substring(m.start(), m.end()));
            pos = m.end();
        }
        
        pos = 0;
        Matcher msgMatcher = JuickMessagesAdapter.msgPattern.matcher(listSelectedItem.Text);
        msgs = null;
        while (msgMatcher.find(pos)) {
            if (msgs == null) { msgs = new ArrayList<String>(); }
            msgs.add(listSelectedItem.Text.substring(msgMatcher.start(), msgMatcher.end()));
            pos = msgMatcher.end();
        }
        
        menuLength = 4;
        
        if (urls != null) {
            menuLength += urls.size();
        }
        if (msgs != null) {
        	menuLength += msgs.size();
        }
        if (listSelectedItem.tags != null) {
        	menuLength += listSelectedItem.tags.size();
        }
        
        if (listSelectedItem.RID == 0) {
            menuLength += 2;
        }
        CharSequence[] items = new CharSequence[menuLength];
        int i = 0;
        if (urls != null) {
            for (String url : urls) { 
            	items[i++] = url; 
            }
        }
        if (listSelectedItem.tags != null) {
            for (String tag : listSelectedItem.tags) {
            	items[i++] = activity.getResources().getString(R.string.View) + " *" + tag; 
            }
        }
        if (msgs != null) {
            for (String msg : msgs) {
            	items[i++] = activity.getResources().getString(R.string.View) + " " + msg; 
            }
        }
        if (listSelectedItem.RID == 0) {
            items[i++] = activity.getResources().getString(R.string.Recommend_message);
            items[i++] = activity.getResources().getString(R.string.Subscribe_to) + " #" + listSelectedItem.MID;
        }
        String UName = listSelectedItem.User.UName;
        
        items[i++] = activity.getResources().getString(R.string.Copy);
        items[i++] = activity.getResources().getString(R.string.blog) + " @" + UName;
        items[i++] = activity.getResources().getString(R.string.Subscribe_to) + " @" + UName;
        items[i++] = activity.getResources().getString(R.string.Blacklist) + " @" + UName;

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setItems(items, this);
        builder.create().show();
        return true;
    }

    public void onClick(DialogInterface dialog, int which) {
        if (urls != null) {
            if (which < urls.size()) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(urls.get(which))));
                return;
            }
            which -= urls.size();
        }
        if (listSelectedItem.tags != null) {
            if (which < listSelectedItem.tags.size()) {
            	String tag = listSelectedItem.tags.get(which);
            	Intent tagIntent = new Intent(activity, MessagesActivity.class);
                tagIntent.putExtra("tag", tag);
                activity.startActivity(tagIntent);
                return;
            }
            which -= listSelectedItem.tags.size();
        }
        if (msgs != null) {
            if (which < msgs.size()) {
            	String msgid = msgs.get(which).substring(1);
            	Intent msgIntent = new Intent(activity, ThreadActivity.class);
                msgIntent.putExtra("mid", Integer.parseInt(msgid));
                activity.startActivity(msgIntent);
                return;
            }
            which -= msgs.size();
        }
        if (listSelectedItem.RID != 0) {
            which += 2;
        }
        switch (which) {
            case 0:
                postMessage("! #" + listSelectedItem.MID, activity.getResources().getString(R.string.Recommended));
                break;
            case 1:
            	postMessage("S #" + listSelectedItem.MID, activity.getResources().getString(R.string.Subscribed));
            	break;
            case 2:
            	ClipboardManager clipboard = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        		clipboard.setText(listSelectedItem.Text);
        		Toast.makeText(activity, activity.getResources().getString(R.string.Copied), Toast.LENGTH_SHORT).show();
            	break;
            case 3:
                Intent i = new Intent(activity, MessagesActivity.class);
                i.putExtra("uid", listSelectedItem.User.UID);
                i.putExtra("uname", listSelectedItem.User.UName);
                activity.startActivity(i);
                break;
            case 4:
                postMessage("S @" + listSelectedItem.User.UName, activity.getResources().getString(R.string.Subscribed));
                break;
            case 5:
                postMessage("BL @" + listSelectedItem.User.UName, activity.getResources().getString(R.string.Added_to_BL));
                break;
        }
    }

    private void postMessage(final String body, final String ok) {
        Thread thr = new Thread(new Runnable() {

            public void run() {
                try {
                    final String ret = MainActivity.postJSON(activity, "http://api.juick.com/post", "body=" + URLEncoder.encode(body, "utf-8"));
                    activity.runOnUiThread(new Runnable() {

                        public void run() {
                            Toast.makeText(activity, (ret != null) ? ok : activity.getResources().getString(R.string.Error), Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    Log.e("postMessage", e.toString());
                }
            }
        });
        thr.start();
    }
}
